package com.ruoyi.system.service;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * SiliconFlow AI服务 (使用DeepSeek-V3模型)
 * 支持按天生成排班，避免JSON截断问题
 *
 * @author ruoyi
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class DeepSeekService {

    @Value("${openrouter.api-key}")
    private String apiKey;

    @Value("${openrouter.model}")
    private String model;

    @Value("${openrouter.base-url}")
    private String baseUrl;

    public String askAI(String question) {
        OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(60, TimeUnit.SECONDS)   // 连接超时
            .readTimeout(120, TimeUnit.SECONDS)      // 读取超时
            .writeTimeout(60, TimeUnit.SECONDS)     // 写入超时
            .callTimeout(120, TimeUnit.SECONDS)      // 整体调用超时（包含所有过程）
            .build();
        MediaType mediaType = MediaType.parse("application/json");

        JSONObject requestParams = new JSONObject();

        // messages
        JSONArray messages = new JSONArray();
        JSONObject systemMsg = new JSONObject();
        systemMsg.set("role", "system");
        systemMsg.set("content", "你是一个专业的警务排班助手。请根据提供的警员信息、班次需求和约束条件，生成合理的排班计划。\n" +
            "\n" +
            "🚨 关键要求（必须严格遵守）：\n" +
            "1. 输出标准JSON格式，不要任何markdown标记\n" +
            "2. scheduleDate字段必须填写具体日期，格式为YYYY-MM-DD，绝对不能为空\n" +
            "3. 所有字段都必须有值，不能为空字符串或null\n" +
            "4. 考虑技能匹配和工作负荷平衡\n" +
            "5. 遵守工作时间限制\n" +
            "6. 确保人员配置合理\n" +
            "7. 用中文回答\n" +
            "\n" +
            "⚠️ 特别注意：scheduleDate字段是必填项，必须使用用户提供的具体日期！\n" +
            "\n" +
            "JSON格式示例（注意日期必须是具体日期）：\n" +
            "{\n" +
            "  \"schedules\": [\n" +
            "    {\n" +
            "      \"officerName\": \"警员姓名\",\n" +
            "      \"officerId\": 123456,\n" +
            "      \"scheduleDate\": \"2025-06-28\",\n" +
            "      \"shiftName\": \"早班\",\n" +
            "      \"timePeriod\": \"06:00-14:00\",\n" +
            "      \"reason\": \"AI智能排班\"\n" +
            "    }\n" +
            "  ]\n" +
            "}\n" +
            "\n" +
            "🔥 重要提醒：scheduleDate字段绝对不能为空，必须使用用户指定的日期！");
        JSONObject userMsg = new JSONObject();
        userMsg.set("role", "user");
        userMsg.set("content", question);
        messages.add(systemMsg);
        messages.add(userMsg);

        // 构建完整对象
        requestParams.set("messages", messages);
        requestParams.set("model", model);
        requestParams.set("max_tokens", 8192);  // 使用DeepSeek-V3的最大限制
        requestParams.set("temperature", 0.7);
        requestParams.set("top_p", 0.9);
        requestParams.set("stream", false);

        RequestBody body = RequestBody.create(requestParams.toString(), mediaType);

        Request request = new Request.Builder()
            .url(baseUrl + "/v1/chat/completions")  // SiliconFlow API路径
            .method("POST", body)
            .addHeader("Content-Type", "application/json")
            .addHeader("Authorization", "Bearer " + apiKey)
            .build();
        try {
            log.info("调用SiliconFlow API，模型: {}", model);
            Response response = client.newCall(request).execute();
            String result = response.body().string();

            if (response.isSuccessful()) {
                log.info("OpenRouter API调用成功");
                return result;
            } else {
                log.error("SiliconFlow API调用失败，状态码: {}, 响应: {}", response.code(), result);
                throw new RuntimeException("AI排班服务调用失败: " + response.code());
            }
        } catch (IOException e) {
            log.error("SiliconFlow API调用异常", e);
            throw new RuntimeException("AI排班服务连接失败", e);
        }
    }

}

